package com.briup.cms.web.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.briup.cms.exception.CustomerException;
import com.briup.cms.utils.JwtUtil;
import com.briup.cms.utils.MessageStatus;
import com.briup.cms.utils.UserInfo;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {

    @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截到请求:" + request.getRequestURI());
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token == null) {
            throw new CustomerException(MessageStatus.USER_TOKEN_NOT_EXIST);
        }
        try {
            JwtUtil.checkSign(token);
        } catch (JWTVerificationException e) {
            throw new CustomerException(MessageStatus.USER_TOKEN_INVALID);
        }

        String uri = request.getRequestURI();
        String method = request.getMethod();
        Map<String, Object> userInfo = JwtUtil.getInfo(token);

        userInfo.put("uri",uri);
        userInfo.put("method",method);
        UserInfo.setUserInfo(userInfo);
        return true;
    }
}
